package club.janna.rpcdemo.server.register;

import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.exception.ZkNodeExistsException;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.PostConstruct;
import java.util.HashSet;
import java.util.Set;

public class ZooKeeperServiceRegister extends LocalServiceRegister {

    private Set<String> registered = new HashSet<>();

    private static final String PATH_PREFIX = "/RPCServices";

    @Value("${discover.zookeeper}")
    private String zookeeperAddress;

    private ZkClient zkClient;

    @PostConstruct
    public void init() {
        zkClient = new ZkClient(zookeeperAddress);
        if(!zkClient.exists(PATH_PREFIX)) {
            try {
                zkClient.createPersistent(PATH_PREFIX);
            } catch(Exception e) {
                // noop
            }
        }
    }

    @Override
    public Object register(String serviceName, Object bean) {
        bean = super.register(serviceName, bean);
        if(!registered.contains(serviceName)) {
            String path = PATH_PREFIX + "/" + serviceName;
            if (!zkClient.exists(path)) {
                try {
                    zkClient.createPersistent(path);
                } catch (ZkNodeExistsException e) {
                    // noop
                }
            }
            zkClient.createEphemeral(path + "/" + "127.0.0.1:12322:JAVA_SERIAL:" + System.currentTimeMillis());
            registered.add(serviceName);
        }
        return bean;
    }
}
